<template>
  <div class="signup-wrapper">
    <el-form ref="signupForm" :model="signupForm" :rules="rules" size="large">
      <div v-if="isVisiable" class="form-content">
        <el-form-item prop="email">
          <el-input
            v-model="signupForm.email"
            clearable
            placeholder="请输入注册邮箱"
          />
        </el-form-item>
        <el-form-item prop="randomCode">
          <el-input v-model="signupForm.randomCode" placeholder="请输入验证码">
            <template v-if="isVisiable" #suffix>
              <p class="random-code" @click="getCode">
                <span>{{ code }}</span>
              </p>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item class="agreement">
          <el-checkbox checked @change="agreementChange">
            同意
            <a href="https://www.baidu.com" target="_block">
              《Colorful注册协议》
            </a>
            &
            <a href="https://www.baidu.com" target="_block"> 《隐私政策》 </a>
          </el-checkbox>
        </el-form-item>
        <el-form-item class="signup-btn">
          <el-button
            type="primary"
            :disabled="isDisabled"
            @click="signup('signupForm')"
          >
            注册
          </el-button>
        </el-form-item>
        <p class="signin" @click="toSignin">已有账号？立即登录</p>
      </div>
      <p v-if="!isVisiable" class="signup-hint">
        邮箱验证码已发送至&nbsp;{{ signupForm.email }}
      </p>
      <div v-if="!isVisiable" class="form-content">
        <el-form-item prop="emailCode">
          <el-input
            v-model="signupForm.emailCode"
            placeholder="请输入邮箱验证码"
          >
            <template v-if="!isVisiable" #suffix>
              <p class="resend">
                <el-button
                  type="text"
                  :disabled="resendDisabled"
                  @click="resendMsgCode"
                >
                  重新发送
                </el-button>
                <span v-if="countdown > 0" class="countdown">
                  {{ countdown }}
                </span>
              </p>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="signupForm.password"
            type="password"
            show-password
            placeholder="8-16位,字母/数字/字符至少包含两种"
          />
        </el-form-item>
        <el-form-item class="finish-btn">
          <el-button type="primary" @click="finish('signupForm')">
            完成
          </el-button>
        </el-form-item>
        <p class="modify-email" @click="modifyEmail">返回修改邮箱</p>
      </div>
    </el-form>
  </div>
</template>

<script>
import Format from "$js/validate";
export default {
  name: "Signup",
  data() {
    let validateRandomCode = (rule, value, callback) => {
      if (!value || value.toLowerCase() !== this.code.toLowerCase()) {
        callback(new Error("验证码错误"));
      } else {
        callback();
      }
    };
    return {
      isVisiable: true,
      isDisabled: false,
      resendDisabled: true,
      countdown: 0,
      code: "",
      timer: null,
      signupForm: {
        email: "",
        password: "",
        randomCode: "",
        emailCode: "",
      },
      rules: {
        email: [
          { validator: Format.FormValidate.Form().Email, trigger: "blur" },
        ],
        randomCode: [{ validator: validateRandomCode, trigger: "blur" }],
        emailCode: [
          { required: true, message: "请输入邮箱验证码", trigger: "blur" },
          { min: 6, max: 6, message: "请输入6位邮箱验证码", trigger: "blur" },
        ],
        password: [
          { validator: Format.FormValidate.Form().Password, trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getCode();
  },
  methods: {
    agreementChange(value) {
      this.isDisabled = !value;
    },
    signup(signupForm) {
      this.$refs[signupForm].validate((valid) => {
        if (valid) {
          this.signupForm.emailCode = "";
          this.signupForm.password = "";
          this.isVisiable = false;
          this.countdownComputed();
        }
      });
    },
    toSignin() {
      this.$emit("signupEmit");
      this.modifyEmail();
    },
    finish(signupForm) {
      this.$refs[signupForm].validate((valid) => {
        if (valid) {
          this.$store.commit("signin", this.signupForm);
          this.$store.commit("setSignStatus", false);
        }
      });
    },
    modifyEmail() {
      this.isVisiable = true;
      this.clearForm();
      this.getCode();
      this.clearTimer();
    },
    countdownComputed() {
      if (!this.timer) {
        this.countdown = 60;
        this.timer = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown--;
          }
          if (this.countdown === 0) {
            this.resendDisabled = false;
            this.clearTimer();
          }
        }, 1000);
      }
    },
    resendMsgCode() {
      this.resendDisabled = true;
      this.countdownComputed();
    },
    getCode() {
      const words =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      const len = words.length;
      this.code = "";
      for (let i = 0; i < 4; i++) {
        this.code += words.charAt(Math.random() * len);
      }
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    clearForm() {
      this.$refs["signupForm"].resetFields();
    },
  },
};
</script>
<style lang="stylus" scoped>
div.form-content {
  text-align: center;
}

p.random-code {
  padding: 0;
}

p.random-code span {
  width: 0.8rem;
  color: #67C23A;
  font-size: 0.16rem;
  font-weight: 800;
  padding: 0 0.1rem;
  background-color: #409eff21;
}

.agreement a {
  color: var(--colorLevel1, #409EFF);
}

p.signup-hint {
  font-size: 14px;
  color: #545c63;
  text-align: center;
}

p.signin, p.modify-email {
  display: inline-block;
  margin: 0.2rem 0;
  transition: all 0.3s;
}

p.signin {
  display: inline-block;
  color: var(--colorLevel2, #8cc5ff);
}

p.signin:hover, p.modify-email:hover, span.countdown {
  color: var(--colorLevel1, #409EFF);
}

p.modify-email {
  color: var(--defaultIconColor, #b5b9bc);
}

p.signin:hover, p.modify-email:hover, p.random-code span:hover {
  cursor: pointer;
}
</style>